package com.easygoods.controller;

import com.bestvike.stone.spring.controller.BaseController;
import com.bestvike.stone.spring.exception.BusinessException;
import com.bestvike.stone.spring.exception.ErrorCode;
import com.bestvike.stone.spring.rest.common.CommonResponse;
import com.bestvike.stone.spring.shiro.annotation.RequiresUser;
import com.easygoods.response.UploadResponse;
import com.easygoods.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhq
 * @date 2019/1/10
 */
@RestController
@RequestMapping("/api/file")
public class FileController extends BaseController {
    @Autowired
    private FileService fileService;

    //文件上传
    //@RequiresUser
    @PostMapping("/upload")
    public CommonResponse<UploadResponse> uploadFile( MultipartFile multipartFile) {
        if (multipartFile.isEmpty())
            throw new BusinessException(ErrorCode.ERROR_SERVER, "文件为空");
        String fileName = multipartFile.getOriginalFilename();
        if (fileName == null)
            throw new BusinessException(ErrorCode.ERROR_SERVER, "未获取到文件名");
        if (!fileName.contains("."))
            throw new BusinessException(ErrorCode.ERROR_SERVER, "请上传带扩展名的文件");

        String fileExt = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
        byte[] fileData;
        try {
            fileData = multipartFile.getBytes();
        } catch (IOException e) {
            this.log.error("获取文件流发生异常", e);
            throw new BusinessException(ErrorCode.ERROR_SERVER, "上传文件失败");
        }

        UploadResponse uploadResponse;
        try {
            uploadResponse = this.fileService.upload(fileData, fileName, fileExt);
        } catch (IOException e) {
            this.log.error("文件上传时发生异常", e);
            throw new BusinessException(ErrorCode.ERROR_SERVER, "上传文件失败");
        }
        return CommonResponse.success(uploadResponse);
    }

    //文件下载
    @RequiresUser
    @GetMapping("/download")
    public void download(@RequestParam("id") String id, HttpServletResponse httpServletResponse) {
        this.fileService.download(id, httpServletResponse);
    }

    //图片预览
    @GetMapping("/preview")
    public void preview(@RequestParam("id") String id, HttpServletResponse httpServletResponse) {
        this.fileService.preview(id, httpServletResponse);
    }
}
